import React, {useState, useEffect} from "react";
import { Button, Form, Input, Select, DatePicker, Space, Image, Table, Col, Row, Tooltip, Switch, Pagination, Tree, message, Modal, Checkbox, Upload, UploadFile, Dropdown, MenuProps } from 'antd';
import {
  SyncOutlined,
  SearchOutlined,
  DownOutlined,
  RightOutlined, WarningOutlined,
} from '@ant-design/icons';
import RoleModal from "./component/roleModal";
import PermissionDistribute from "./component/permissionDistribute";
import { useTranslation } from 'react-i18next';
import { apiInterceptors, getRole, deleteRoleById, updateRole as updateRoleById} from '@/client/api';
import useSetTableScroll from '@/hooks/use-table-scroll'

const { confirm } = Modal

const User = () => {
  const [queryForm] = Form.useForm();
  const { t } = useTranslation();

  const [handleType, setHandleType] = useState('add')
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isPermissionOpen, setPermissionOpen] = useState(false)
  const [tableData, setTableData] = useState([])
  const tableHeight = useSetTableScroll()
  let [pagination, setPagination] = useState({
    total: 0,
    page_num: 1,
    page_size: 10
  })
  let [roleId, setRoleId] = useState('')

  const columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '租户名称',
      dataIndex: 'tenant_name',
      key: 'tenant_name',
    },
    {
      title: '创建人姓名',
      dataIndex: 'creation_name',
      key: 'creation_name',
    },
    {
      title: '创建人ldap',
      dataIndex: 'creation_account',
      key: 'creation_account',
    },
    // {
    //   title: '应用名称',
    //   dataIndex: 'app_name',
    //   key: 'app_name',
    // },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (_:any, record:any) => {
        return record.status === '1' ? '启用' : '禁用'
      }
    },
    {
      title: '操作',
      render: (_:any, record:any) => (
        <Space size="middle">
          <a onClick={() => updateRole(record)}>修改</a>
          {
            record.status === '0' ?
              <a onClick={() => statusHandle(record, '1')}>启用</a>
              :
              <a onClick={() => statusHandle(record, '0')}>禁用</a>
          }
          {/*<a onClick={() => deleteRole(record)}>删除</a>*/}
          <a onClick={() => permissionHandle(record)}>权限分配</a>
        </Space>
      )
    }
  ]

  const paginationChange = (page:number, size:number) => {
    const {total} = pagination
    setPagination({
      total: total,
      page_num: page,
      page_size: size
    })
  }
  function searchQueryFn() {
    setPagination({ ...pagination, page_num: 1 })
    getTableData()
  }
  function resetQueryFn() {
    queryForm.resetFields()
    searchQueryFn()
  }
  function setModal(e:boolean) {
    setIsModalOpen(e)
  }
  const updateRole = (data:any) => {
    setRoleId(data.id)
    setHandleType('edit')
    setModal(true)
  }
  const deleteRole = (data:any) => {
    confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: `你确定删除该角色吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk() {
        const [err] = await apiInterceptors(deleteRoleById(data.id))
        if (!err) {
          message.success('操作成功')
          searchQueryFn()
        }
      },
    });
  }
  const statusHandle = async (record, type) => {
    confirm({
      title: t('Tips'),
      icon: <WarningOutlined />,
      content: `你确定${record.status === '1' ? '禁用' : '启用'}该用户吗?`,
      okText: 'Yes',
      okType: 'danger',
      cancelText: 'No',
      async onOk() {
        const [err] = await apiInterceptors(updateRoleById({ status: type, id: record.id }))
        if (!err) {
          message.success('操作成功')
          searchQueryFn()
        } else {
          return
        }
      },
    });
  }
  const permissionHandle = (record) => {
    setRoleId(record.id)
    setPermissionOpen(true)
  }
  const createHandle = () => {
    setModal(true)
    setHandleType('add')
  }
  const getTableData = async() => {
    const queryData = queryForm.getFieldsValue()
    const param = {
      ...pagination,
      ...queryData,
    }
    delete param.total

    const [_, data] = await apiInterceptors(getRole(param))
    setTableData(data?.data)
    setPagination({
      total: data?.total,
      page_size: pagination.page_size,
      page_num: data?.page
    })
  }
  useEffect(() => {
    getTableData()
  }, [pagination.page_size, pagination.page_num])
  return (
    <div className="p-5 marvel_table_container">
      <div className="top_search p-5 bg-white dark:bg-[#232734]">
        <Form form={queryForm} layout="inline" name={'query'} autoComplete="off" className='cus_form'
              initialValues={{status: '1'}}
              labelAlign='left'
        >
          {/*<Space wrap={true}>*/}
          <Form.Item label="角色ID" name="id">
            <Input style={{ width: 240 }} placeholder="请输入角ID" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          <Form.Item label="角色名称" name="name">
            <Input style={{ width: 240 }} placeholder="请输入角色名称" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          {/*<Form.Item label="租户ID" name="tenant_id">*/}
          {/*  <Input style={{ width: 240 }} placeholder="请输入租户ID" allowClear onPressEnter={searchQueryFn} />*/}
          {/*</Form.Item>*/}
          {/*<Form.Item label="租户名称" name="tenant_id">*/}
          {/*  <Input style={{ width: 240 }} placeholder="请输入租户名称" allowClear onPressEnter={searchQueryFn} />*/}
          {/*</Form.Item>*/}
          <Form.Item label="创建人ldap" name="creation_account">
            <Input style={{ width: 240 }} placeholder="请输入创建人ldap" allowClear onPressEnter={searchQueryFn} />
          </Form.Item>
          {/*<Form.Item label="应用名称" name="App_name">*/}
          {/*  <Input style={{ width: 240 }} placeholder="请输入应用名称" allowClear onPressEnter={searchQueryFn} />*/}
          {/*</Form.Item>*/}
          <Form.Item label="状态" name="status">
            <Select
              style={{ width: 240 }}
              placeholder="请选择状态"
              onChange={searchQueryFn}
              options={[
                { value: '1', label: '启用' },
                { value: '0', label: '禁用' },
              ]}
            />
          </Form.Item>
          <Form.Item label=''>
            <div style={{width: 240}}>
              <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />} style={{marginRight: '20px'}}>
                搜索
              </Button>
              <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                重置
              </Button>
            </div>
          </Form.Item>
          {/*</Space>*/}
        </Form>
      </div>
      <Button type="primary" style={{marginTop: '20px'}} onClick={() => createHandle()}>创建角色</Button>
      <div className="user_table" style={{marginTop: '20px'}}>
        <Table
          columns={columns}
          dataSource={tableData}
          scroll={{y: tableHeight}}
          pagination={{
            total: pagination.total,
            showTotal: (total, range) => `共 ${total} 条`,
            onChange: paginationChange
          }}
        />
      </div>
      {
        isModalOpen &&
        <RoleModal handleType={handleType} isModalOpen={isModalOpen} setModal={ setModal } successCall={ searchQueryFn } roleId={ roleId }/>
      }
      {
        isPermissionOpen &&
        <PermissionDistribute roleId={roleId} setModal={ setPermissionOpen } successCall={searchQueryFn}/>
      }
    </div>
  )
}

export default User
